package com.frxuexi.mymvi

import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.AsyncImage
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

@SuppressLint("CoroutineCreationDuringComposition")
@OptIn
@Composable
fun NewsPage(name:String,vm: NewsViewModel= hiltViewModel(),
             scope: CoroutineScope = rememberCoroutineScope()) {
//    val scope2: CoroutineScope = rememberCoroutineScope()

    var list = remember {
        SnapshotStateList<NewsEntity>()
    }

    scope.launch {
        vm.state.collect{
            when(it){
                is NewsState.onSuccess->{
                    Log.i("===",it.list.toString())
                    list.addAll(it.list)
                }
                is NewsState.onError->{
                    Log.i("===",it.msg)
                }
                else->{}
            }
        }
    }

    scope.launch {
        //发送意图
        vm.channel.send(NewsIntent.getNews(1))
    }

    Column {
        Text(text = "欢迎$name")
        LazyColumn(modifier=Modifier.padding(20.dp)){
            items(list){
                NewsItem(it)
            }
        }
    }

    

}

@Composable
fun NewsItem(news:NewsEntity){
    Column {
        AsyncImage(model = news.imgurl, contentDescription = "",
            contentScale= ContentScale.Crop,
            modifier= Modifier
                .fillMaxWidth()
                .clip(RoundedCornerShape(20.dp)))
        Spacer(modifier = Modifier.height(5.dp))
        Text(text = news.title)
    }
}